﻿using Ah.Testudin.Engine.Actors;

using Microsoft.Xna.Framework;

namespace Ah.Testudin.Engine.Graphics.Scenes.SceneNodes.Cameras
{
    public class ThirdPersonCameraSceneNode : SceneNodeBase, ICameraSceneNode
    {
        #region Private Member Variables

        private readonly ISceneNode _target;

        private readonly Vector3 _targetOffset;

        #endregion

        #region Constructors

        public ThirdPersonCameraSceneNode(
            ActorId actorId,
            Matrix projection,
            ISceneNode target,
            Vector3 targetOffset)
            : base("Third Person Camera", actorId, RenderPass.StaticActor, Matrix.Identity)
        {
            this.Projection = projection;

            _target = target;

            _targetOffset = targetOffset;
        }

        #endregion

        #region ICameraSceneNode

        public Matrix Projection { get; private set; }

        public Matrix View { get; private set; }

        #endregion

        #region SceneNodeBase

        public override void Render(Scene scene)
        {
            Matrix targetTransform = _target.Properties.ToWorldTransform;

            Matrix transform = Matrix.Identity;

            transform.Forward = Vector3.Normalize(targetTransform.Forward);

            transform.Up = Vector3.Normalize(targetTransform.Up);

            transform.Right = Vector3.Cross(
                targetTransform.Up,
                targetTransform.Forward);

            Vector3 position = targetTransform.Translation +
                Vector3.TransformNormal(
                    _targetOffset,
                    transform);

            this.View = Matrix.CreateLookAt(
                position,
                targetTransform.Translation,
                targetTransform.Up);
        }

        #endregion
    }
}
